package com.study.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.ssl.SslContext;

public class WebSocketHandlerInit extends ChannelInitializer<SocketChannel> {

    private static final String WEBSOCKET_PATH = "";
    private final SslContext sslContext;
    private final ChannelGroup channelGroup;

    public WebSocketHandlerInit(SslContext sslContext, ChannelGroup channelGroup) {
        this.sslContext = sslContext;
        this.channelGroup = channelGroup;
    }

    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        // SSL的http请求handler
        if (sslContext != null) {
            pipeline.addLast(sslContext.newHandler(ch.alloc()));
        }
        // 增加对http的支持
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new HttpObjectAggregator(65536));
        // Netty提供 支持websocket应答数据压缩传输
        pipeline.addLast(new WebSocketServerCompressionHandler());
        // Netty提供 对整个websocket的通信进行了初始化
        // 发现http请求报文中有升级为websocket的请求，包括握手以及以后的一些通信控制、心跳等
        pipeline.addLast(new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true));
        // 浏览器访问时展示的页面
        pipeline.addLast(new WsIndexPageHandler(WEBSOCKET_PATH));
        // 处理websocket数据
        pipeline.addLast(new WsFrameHandler(channelGroup));
    }
}
